//
//  DropDownView.m
//  Bus
//
//  Created by wangjiajia on 13-11-15.
//  Copyright (c) 2013年 wangjiajia. All rights reserved.
//

#import "DropDownView.h"
#import "WFForm.h"
#import "AutoScrollUILabel.h"
@implementation DropDownView

@synthesize tv,tableArray,textField;

- (void)dealloc

{
    //[tv release];
    //[tableArray release];
    //[textField release];
}

//xib方式加载，默认调用init方法，这里需要人为导向initWithFrame。事实上上 根本没加载....
/*
 - (id)init
 {
 NSLog(@"DropDownView init");
 self =  [self initWithFrame:CGRectMake(0,0, 320, 30)];
 return self;
 }
 */
-(id)initWithFrame:(CGRect)frame

{

    //NSLog(@"DropDownView initWithFrame");
    //确保整个UI高度 至少是200
    if (frame.size.height<200) {
        frameHeight = 200;
    }else{
        frameHeight = frame.size.height;
    }
    //下拉列表高度：总高度-文本控件高度
    tabheight = frameHeight-30.0f;
    //固定文本控件高度为：30
    frame.size.height = 30.0f;
    self=[super initWithFrame:frame];
    if(self){
        showList = NO; //默认不显示下拉框
        //1、tableViwe初始化
        tv = [[UITableView alloc] initWithFrame:CGRectMake(10, 30, frame.size.width-20, 0)];
        tv.delegate = self;//代理可以考虑由外部提供,但是那样就无法访问内部的textField控件了
        tv.dataSource = self;
        tv.backgroundColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:0.3];
        tv.separatorColor = [UIColor brownColor];
        tv.hidden = YES;
        [self addSubview:tv];
        
        //2、textField初始化
        textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 30)];
        textField.borderStyle=UITextBorderStyleRoundedRect;//设置文本框的边框风格
        [textField setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
        textField.font = [UIFont fontWithName:@"-" size:18.0f];
        textField.textColor=[UIColor blackColor];
        textField.textAlignment=UITextAlignmentCenter;
        textField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
        
        //textField.text=@"所有表单类型";//手动设置初始化的文字,写在调用端,这里不要写死了。
        //textField.inputView=[[UIView alloc] initWithFrame:CGRectZero];//隐藏键盘的有效方式一:只有光标,没有键盘
        textField.delegate=self;//方式二:没有光标和键盘
        //方式三:失败
        //[textField addTarget:self action:@selector(regisnFirstResponderTag) forControlEvents:UIControlEventAllEvents];//事件响应
        //[textField addTarget:self action:@selector(regisnFirstResponderTag) forControlEvents:UIControlEventAllTouchEvents];//事件响应
        //[textField addTarget:self action:@selector(regisnFirstResponderTag) forControlEvents:UIControlEventAllEditingEvents];//事件响应
        
        [textField addTarget:self action:@selector(dropdown) forControlEvents:UIControlEventTouchDown];//事件响应。UIControlEventTouchUpInside事件不可以，因为禁用了编辑，根本点击不进去
        [self addSubview:textField];
    }
    return self;
}
#pragma mark- 禁用键盘
//-(void)textFieldDidBeginEditing:(UITextField *)textFieldtag{
//    [textFieldtag resignFirstResponder];//刚开始编辑就立即放弃编辑,隐藏键盘
//}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return NO;
}

-(void)regisnFirstResponderTag{
    NSLog(@"resignFirstResponder");
    [textField resignFirstResponder];
}
#pragma mark- 下拉逻辑核心
-(void)dropdown{
    //NSLog(@"dropdown");
    //UIControlEventAllEvents 则 3次调用 结果是： 显示->隐藏->显示 或 隐藏->显示->隐藏
    //UIControlEventTouchUpInside|UIControlEventEditingDidEnd 则 弹出键盘
    //UIControlEventEditingDidBegin 一开始就处理，IOS6 OK,IOS7 notOK
    //UIControlEventTouchDown IOS7 notOK,IOS6 未知，应该也notOK
    [textField resignFirstResponder];
    
    if (showList) {
        //一:如果下拉框已显示，什么都不做
        //return;
        
        //二:显示则隐藏
        //1、隐藏下拉框
        //NSLog(@"隐藏");
        //tv.hidden = YES;//立即隐藏，动画失效.可以在setAnimationDidStopSelector中隐藏。不设置也没啥。
        showList = NO;
        //2、动画隐藏下拉列表
        [UIView beginAnimations:@"ResizeForKeyBoard2" context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        //[UIView setAnimationDuration:5];
        //下拉框
        CGRect frame = tv.frame;
        frame.size.height = 0;
        tv.frame = frame;
        //自身框
        CGRect sf = self.frame;//{{0, 0}, {320, 300}}
        //NSLog(@"显示时候%@",NSStringFromCGRect(sf));
        sf.size.height = 30;//设置frameHeight的基面高度 确保高度>30时能点击
        self.frame = sf;
        [UIView commitAnimations];
    }else {
        //如果下拉框尚未显示，则进行显示
        //NSLog(@"显示");
        //1、把dropdownList放到前面，防止下拉框被别的控件遮住
        [self.superview bringSubviewToFront:self];
        //2、显示下拉框
        tv.hidden = NO;
        showList = YES;
        //3、动画展示下拉列表
        [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        //[UIView setAnimationDuration:5];
        //下拉框
        CGRect frame = tv.frame;
        frame.size.height = 0;
        tv.frame = frame;//设动画点1 值拷贝
        frame.size.height = tabheight;
        tv.frame = frame;//设动画点2 值拷贝
        //自身框
        CGRect sf = self.frame;//{{0, 0}, {320, 30}}
        sf.size.height = frameHeight;//设置frameHeight的基面高度 确保高度>30时能点击
        self.frame = sf;
        
        [UIView commitAnimations];
    }
}

#pragma mark - 据源实现方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{
    return [tableArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
        cell.backgroundColor=[UIColor clearColor];
        //cell.textLabel.font=[UIFont fontWithName:@"-" size:20];
        //cell.detailTextLabel.font=[UIFont fontWithName:@"-" size:20];
    }
    if(tableArray.count<=0){
        return cell;
    }
    NSString* word=[[tableArray objectAtIndex:[indexPath row]] description];//bean对象需要重写description方法
    //1、使用自带的textLabel
    /*
     cell.textLabel.text = word;
     // cell.textLabel.font = [UIFont systemFontOfSize:20.0f];
     cell.textLabel.font = [UIFont fontWithName:@"Arial" size:20];
     
     cell.textLabel.backgroundColor=[UIColor clearColor];
     cell.textLabel.textColor=[UIColor blackColor];
     cell.textLabel.adjustsFontSizeToFitWidth=YES;
     */
    
    //2、使用AutoScrollUILabel
    float wordWidth=[word sizeWithFont:[UIFont fontWithName:@"-" size:18]].width;
    AutoScrollUILabel* textScrollLabel=[[AutoScrollUILabel alloc] initWithFrame:CGRectMake(0, 0, wordWidth, 30)];
    textScrollLabel.font= [UIFont fontWithName:@"-" size:18];
    textScrollLabel.text=word;
    //垂直居中没有直接的属性
    textScrollLabel.backgroundColor=[UIColor clearColor];
    //重用前 先清空原来的 否则 重影
    for(UIView* subView in cell.contentView.subviews){
        [subView removeFromSuperview];
    }
    [cell.contentView addSubview:textScrollLabel];
    //NSLog(@"共有子视图%d个",cell.contentView.subviews.count);//不断地累加
    //cell.textLabel=textScrollLabel;//error 赋值给只读属性
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    
    return cell;
    
}
#pragma mark - 代理实现方法
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
    return 35;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{
    [self.textField resignFirstResponder];
    //NSLog(@"didSelectRowAtIndexPath");
    NSString* newFormName = [[tableArray objectAtIndex:[indexPath row]] description];
    NSString* oldFormName=textField.text;
    textField.text=newFormName;
    textField.adjustsFontSizeToFitWidth=YES;
    showList = NO;
    //tv.hidden = YES;
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    //重置控件高度
    CGRect sf = self.frame;
    sf.size.height = 30;
    self.frame = sf;
    //重置列表高度
    CGRect frame = tv.frame;
    frame.size.height = 0;
    tv.frame = frame;
    [UIView commitAnimations];
    //判断是否发送 改变的 广播
    if(![oldFormName isEqualToString:newFormName]){
        
        [[NSNotificationCenter defaultCenter] postNotificationName:self.postNotificationName object:[NSString stringWithFormat:@"%d", [indexPath row]]];
    }
    
    //判断是否滚动显示字符 about 3 hours。。。
    //    float wordWidth=[formName sizeWithFont:[UIFont fontWithName:@"Arial"size:20]].width;
    //    float screenWidth=[UIScreen mainScreen].bounds.size.width;
    //    NSLog(@"wordWidth=%f,screenWidth=%f",wordWidth,screenWidth);
    //
    //    if(wordWidth>screenWidth){
    //        //core animaiton
    //        [UIView beginAnimations:@"pao_ma_deng" context:nil];
    //        [UIView setAnimationDuration:10.0f * (wordWidth / screenWidth )];
    //        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    //        //[UIView setAnimationDelegate:self];
    //        //[UIView setAnimationRepeatAutoreverses:YES];
    //        [UIView setAnimationRepeatCount: 10];
    //        CGRect frameStart =CGRectMake(screenWidth, 0, wordWidth, 30);
    //        self.textField.frame=frameStart;//相对父视图的坐标
    //        self.textField.text=formName;//此时足够长，应该没有...了
    //
    //        CGRect frameEnd =CGRectMake(-wordWidth, 0, wordWidth, 30);
    //        self.textField.frame=frameEnd;
    //        [UIView commitAnimations];
    //    }else{
    //
    //        textField.text=formName;
    //    }
    
}

#pragma mark

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
